<?php
/*
 * @Author: lokei
 * @Date: 2022-08-27 10:56:02
 * @LastEditors: lokei
 * @LastEditTime: 2023-02-10 15:58:05
 * @Description: 
 */
namespace App\Http\Controllers\Ucenter\Fans;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Models\Platform\ConfModel;
use App\Models\Ucenter\FansModel;
use App\Models\Ucenter\UserModel;
use App\Services\Ucenter\FansService;
use Illuminate\Http\Request;

use GuzzleHttp;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Facades\JWTAuth;

class FansController extends Controller {
    
    private FansService $fans_service;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
        $this->fans_service = new FansService();
    }

    public function list(Request $request) {
        if($request->input('nickname') != null && $request->input('nickname') != '') {
            $model = FansModel::where('nickname', 'LIKE', "%{$request->input('nickname')}%");
        }
        if($request->input('limit') != null && $request->input('limit') != '') {
            if(isset($model)) {
                $model->limit($request->input('limit'))->offset((intval($request->input('page')) - 1) * intval($request->input('limit')));
            } else {
                $model = FansModel::limit($request->input('limit'))->offset((intval($request->input('page')) - 1) * intval($request->input('limit')));
            }
        }
        if(isset($model)) {
            $items = $model->orderBy('followtime', 'desc')->get();
        } else {
            $items = FansModel::orderBy('followtime', 'desc')->get();
        }
        $res = ResultTool::success();
        $res['data']['items'] = $items;
        $res['data']['total'] = FansModel::count();
        return $res;
    }

    public function ofUser(Request $request) {
        if($request->input('uid') != null && $request->input('uid') > 0) {
            $user = UserModel::where('uid', '=', $request->input('uid'))->first();
        } else if ($request->input('token') != null && $request->input('token') != '') {
            $user = JWTAuth::setToken($request->input('token'))->authenticate();
        }
        if(is_null($user)) {
            $res = ResultTool::fail();
            $res['errorMsg'] = '非平台用户！';
            return $res;
        }
        $fans = FansModel::where('uid', '=', $user->uid)->where('platform', '=', $request->input('platform'))->first();
        $res = ResultTool::success();
        $res['data'] = $fans;
        return $res;
    }

    public function bindUser(Request $request) {
        if($request->input('uid') != null && $request->input('uid') > 0) {
            $user = UserModel::where('uid', '=', $request->input('uid'))->first();
        } else if ($request->input('token') != null && $request->input('token') != '') {
            $user = JWTAuth::setToken($request->input('token'))->authenticate();
        }
        if(is_null($user)) {
            $res = ResultTool::fail();
            $res['errorMsg'] = '非平台用户！';
            return $res;
        }
        $http = new GuzzleHttp\Client;
        if (config('app.proj_identity') != null && config('app.proj_identity') != '') {
            $endapp = Redis::get('proj:' . config('app.proj_identity') . ':mp');
            $endapp_info = json_decode($endapp);
            $params = [
                'appid' => $endapp_info->appid,
                'secret' => $endapp_info->secret,
                'code' => $request->input('code'),
                'grant_type' => 'authorization_code'
            ];
        } else {
            $conf = ConfModel::first();
            $params = [
                'appid' => $conf->mp_appid,
                'secret' => $conf->mp_secret,
                'code' => $request->input('code'),
                'grant_type' => 'authorization_code'
            ];
        }
        $response = $http->get('https://api.weixin.qq.com/sns/oauth2/access_token', [
            'query' => $params
        ]);
        $result = json_decode($response->getBody(), true);
        if (array_key_exists('errcode', $result) && $result['errcode'] != 0) {
            $res = ResultTool::fail();
            $res['errorCode'] = $result['errcode'];
            $res['errorMsg'] = $result['errmsg'];
            return $res;
        }
        if (array_key_exists('openid', $result) && $result['openid'] != '') {
            $fans = FansModel::where('openid', '=', $result['openid'])->where('platform', '=', 'mp')->first();
            if (!is_null($fans)) {
                $fans->uid = $user->uid;
                $fans->save();
            } else {
                $this->fans_service->registerOpenid('mp', $result['openid']);
                $fans = FansModel::where('openid', '=', $result['openid'])->first();
                $fans->uid = $user->uid;
                $fans->save();
            }
        }
        return ResultTool::success();
    }

    public function rebindUser(Request $request) {
        $fans = FansModel::where('openid', '=', $request->input('openid'));
        if(!is_null($fans)) {
            $user = UserModel::where('mobile', '=', $request->input('mobile'))->first();
            if(!is_null($user)) {
                $fans->uid = $user->uid;
                $fans->save();
                return ResultTool::success();
            }
        }
        return ResultTool::fail();
    }

    public function delete(Request $request) {
        FansModel::where('fid', '=', $request->input('fid'))->delete();
        return ResultTool::success();
    }
}